package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.utils.BooleanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstans;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-12-27
 */
@Service
@RequiredArgsConstructor
public class RedisLikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 点赞或者取消点赞(改为使用reids合并写请求，提高响应速度)
     * @param dto
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
       //判断是点赞还是取消点赞
        //创建key和value
        String key = RedisConstans.LIKED_RECORDS + dto.getBizId();
        String value = UserContext.getUser().toString();
        Long result = 0L;
        if (dto.getLiked()) {
            //点赞
            result = redisTemplate.opsForSet().add(key, value);
        } else {
            //取消点赞
            result = redisTemplate.opsForSet().remove(key, value);
        }
        if (result == null || result == 0) {
            return;
        }
        //使用redis的zset存储点赞数量
        Long size = redisTemplate.opsForSet().size(key);
        if (size == null){
            return;
        }
        key = RedisConstans.LIKED_TIMES + dto.getBizType();
        value = dto.getBizId().toString();
        //存储到zset集合中
        redisTemplate.opsForZSet().add(key, value, size.doubleValue());
    }


    /**
     * 批量查询点赞状态
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        //判断当前用户是否已经点过赞，
        Long userId = UserContext.getUser();
        List<Object> resultList = redisTemplate.executePipelined((RedisCallback<?>) conn -> {
            StringRedisConnection src = (StringRedisConnection) conn;
            for (Long bizId : bizIds) {
                String key = RedisConstans.LIKED_RECORDS + bizId;
                src.sIsMember(key, String.valueOf(userId));
            }
            return null;
        });
        //遍历集合，获得哪个用户点过赞了
        Set<Long> list = new HashSet<>();
        for (int i = 0; i < resultList.size(); i++) {
            Boolean result = (Boolean) resultList.get(i);
            if (BooleanUtils.isTrue(result)){
                list.add(bizIds.get(i));
            }
        }
        return list;
    }
}

